import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class SaveServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 解决中文乱码
        request.setCharacterEncoding("UTF-8");

        // 获取表单提交的数据
        String usercode = request.getParameter("usercode");
        String username = request.getParameter("username");

        // JDBC
        Connection conn = null;
        PreparedStatement ps = null;
        int count = 0;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true"
            , "root", "991025");
            conn.setAutoCommit(false);
            String sql = "insert into t_user(usercode, username) values (?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1, usercode);
            ps.setString(2, username);
            count = ps.executeUpdate();
            conn.commit();
        } catch (Exception e) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            System.out.println(count);
            if (count == 1) {
                // 保存成功
                // 跳转到成功页面
                // 转发
//                request.getRequestDispatcher("/success.html").forward(request, response);
                // 重定向
                response.sendRedirect(request.getContextPath() + "/success.html");
            }
        }

    }
}
